package com.ja.util;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.server.HandshakeInterceptor;

import com.ja.controller.ChatWebSocketHandlerht;
import com.ja.domain.AdminUser;
/**
 * 项目名称：cp   
 * 类名称：WebSocketHandshakeInterceptorht.java   
 * 类描述：   后台websocket 拦截器
 * 创建人：   WCH
 * 创建时间：2019年2月27日 下午3:01:40   
 * @version v1.0.0
 */

public class WebSocketHandshakeInterceptorht implements HandshakeInterceptor {

	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Map<String, Object> attributes) throws Exception {
		if(request instanceof ServletServerHttpRequest) {
			 ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
			 HttpSession httpSession = servletRequest.getServletRequest().getSession(false);
			 if (httpSession != null) {  
				 AdminUser admin1 = (AdminUser)httpSession.getAttribute("admin1");
				 if(admin1==null){
					 return false;
				 }
				 if(ChatWebSocketHandlerht.sessions.size() >= 1) {
					 for(WebSocketSession w : ChatWebSocketHandlerht.sessions) {
						 if(w.getAttributes().get("admin").equals(admin1.getName())) {
							 return false;
						 }else {
							 attributes.put("admin",admin1.getName()); 
						 }
					 }
				 }else {
						 attributes.put("admin",admin1.getName());
				 }
	            }else{  
	            	 return false;
	            }  
		}
		return true;
	}

	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Exception exception) {
		
	}

}
